<%--
  Created by IntelliJ IDEA.
  User: 15154
  Date: 2020/10/10
  Time: 15:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="../resources/layui/css/layui.css">
</head>
<body>
<!-- 搜索条件开始 -->
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>查询条件</legend>
</fieldset>
<form id="searchFrm" class="layui-form" method="post">
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">学号:</label>
            <div class="layui-input-inline">
                <input type="text" name="stuNumber" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">楼栋号:</label>
            <div class="layui-input-inline">
                <input type="text" name="buildNumber"  autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline" style="margin-left: 400px;">
            <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-search" id="doSearch">查询</button>
            <button type="reset" class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">重置</button>
        </div>
    </div>
</form>

<!-- 搜索条件结束 -->


<!-- 数据表格开始 -->
<table class="layui-hide" id="userTable" lay-filter="userTable"></table>
<div style="display: none;" id="userToolBar">
    <button type="button" class="layui-btn layui-btn-sm" lay-event="batchDelete">批量删除</button>
</div>
<div  id="userBar" style="display: none;">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</div>
<!-- 数据表格结束 -->


<script src="../resources/layui/layui.js"></script>
<script type="text/javascript">
    layui.use([ 'jquery', 'layer', 'form', 'table'], function() {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var url;
        var mainIndex;
        //渲染数据表格
        var tableIns = table.render({
            elem:'#userTable',//渲染的目标对象
            url:'/selectUsers'//数据接口
            ,toolbar:'#userToolBar'//表格的工具条
            ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,page:true//开启分页
            ,limit:5//每页的数据量(初始值)
            ,limits:[5,10,15,20]//可以选择的每页数据量
            ,cols: [[//列表数据
                {type:'checkbox',fixed:'left'}
                ,{field:'stuId',  title: 'ID', sort: true}
                ,{field:'stuNumber',  title: '学号', sort: true}
                ,{field:'stuName',  title: '姓名'}
                ,{field:'passWord',  title: '密码'}
                ,{field:'sex',  title: '性别'}
                ,{field:'buildNumber',  title: '楼栋号'}
                ,{field:'money',  title: '积分'}
                ,{field:'tel',  title: '电话'}
                ,{fixed:'right',title:'操作',toolbar:'#userBar',width:220,align:'center'}
            ]]
        });


        //模糊查询
        $('#doSearch').click(function () {
            url = '/select';
            //获取到搜索框里面输入的内容
            var params = $('#searchFrm').serialize();
            /*$.post(url,params,function (obj) {
                layer.msg();
                //重新渲染，重新渲染的是当前页的所有用户
                tableIns.reload();
            })*/
            tableIns.reload({
                url:url+'?'+params
            })

        })

        //头部工具栏监听事件
        table.on('toolbar(userTable)', function(obj){
            //var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    openAddUser();
                    break;
                case 'batchDelete':
                    batchDelete();
                    break;
            };
        });

        //监听工具条
        table.on('tool(userTable)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

            if(layEvent === 'del'){ //删除
                layer.confirm('真的删除行么', function(index){
                    deleteUser(data.id);
                });
            } else if(layEvent === 'edit'){ //编辑
                //打开修改的弹出层
                openUpdateUser(data);
            }
        });

        $.get({
            url:'/user/getNewId',
            dataType:'text',
            success:function (data) {
                console.log(data);
                $("#id").val(data);
            }
        })

        //打开添加页面的方法
        function openAddUser() {
            mainIndex = layer.open({
                type:1,
                title:'添加用户',
                content:$('#saveOrUpdateDiv'),
                area:['800px','400px'],
                success:function (index) {
                    //清空表单数据
                    $('#dataFrm')[0].reset();
                    url='/user/addUser';
                    var res = $.get('/user/getNewId',function (obj) {
                        $('#userid').val(res.responseText)
                    });
                }
            })
        }


        $.get({
            url:'/user/getUserRole',
            dataType:'json',
            success:function (result) {
                var html = "";
                for (var i = 0; i < result.length; i++) {
                    html+="<option value='"+result[i].id+"'>"+result[i].role+"</option>"
                }
                $("[name='role']").append(html);
                form.render("select");
            }
        });


        //批量删除的方法
        function batchDelete() {
            //得到选中的数据
            var checkStatus = table.checkStatus('userTable');
            var data = checkStatus.data;
            url = '/user/deleteUsers';
            var params = "";
            $.each(data,function (index, elem) {
                if(index==0){
                    params+='ids='+elem.id;
                }else {
                    params+='&ids='+elem.id;
                }
            });
            layer.confirm('真的要删除这些用户信息吗?',function (index) {
                var res = $.post(url,params,function () {
                    layer.msg(res.responseText);
                    tableIns.reload();
                })
            })
        }

        //删除用户
        function deleteUser(id){
            url = '/user/deleteUser';
            var res = $.post(url,{'id':id},function (obj) {
                //提示删除成功与否
                layer.msg(res.responseText);
                //刷新数据表格
                tableIns.reload();
            })
        }

        //打开修改页面
        function openUpdateUser(data){
            mainIndex = layer.open({
                type:1,
                title:'修改用户',
                content:$('#saveOrUpdateDiv'),
                area:['800px','400px'],
                success:function (index) {
                    form.val('dataFrm',data);
                    url = '/user/editUser';
                }
            })
        }

        //提交按钮的监听事件
        form.on('submit(doSubmit)',function (obj) {
            //序列化表单数据
            //url?id=xx&username=xx&password=xx
            var params = $('#dataFrm').serialize();
            var res = $.post(url,params,function (obj) {
                //异步请求成功之后要做的事情
                //关闭弹出层
                layer.close(mainIndex);
                //显示添加与否
                layer.msg(res.responseText);
                //刷新数据表格
                tableIns.reload();
            })
        })
    });
</script>
</body>
</html>
